<template>
  <view class="product-page">
    <!-- 顶部公司信息 -->
    <view class="company-info">
      <view class="brand-name">{{ supplierInfo.brand_name }}</view>
    </view>

    <!-- 商品列表 -->
    <scroll-view 
      class="product-scroll" 
      scroll-y 
      @scrolltolower="loadMore"
      :style="{ height: scrollHeight * 2 + 'rpx' }"
      :show-scrollbar="false"
    >
      <view class="product-grid">
        <view
          class="product-item"
          v-for="(goods, index) in goodsList"
          :key="index"
          @click="toGoodsDetail(goods.id)"
        >
          <image
            class="product-image"
            :src="goods.goods_image"
            mode="fill"
            lazy-load
          ></image>
          <view class="product-title">{{ goods.product_name }}</view>
        </view>
      </view>
      
      <view style="height: 94rpx"></view>
    </scroll-view>

    <view class="empty-order" v-if="goodsList.length === 0">
      <gui-image src="https://cphimg.leyoo888.com/dev/carry_upload/supplier/2025-06-11/1749606259704.png?x-oss-process=image/resize,w_200,h_200" />
    </view>

    <!-- 底部固定店铺信息 -->
    <view class="shop-footer" v-if="supplierInfo.id">
      <view class="shop-info">
        <image class="shop-logo" :src="supplierInfo.logo" mode="fill"></image>
        <div style="flex: 1; align-self: flex-start">
          <view class="shop-detail">
            <view class="shop-name">{{ supplierInfo.name }}</view>
            <view class="shop-address">{{ supplierInfo.address }}</view>
          </view>
          <view class="shop-actions">
            <view
              class="action-btn contact-btn"
              @click="callPhone(supplierInfo.phone)"
              >拨打电话</view
            >
            <view
              :class="['action-btn', supplierInfo.audit_status !== 2 ? 'order-btn' : 'switch-btn']"
              @click="supplierInfo.audit_status !== 2 ? bindSupplierClick() : ()=>{}"
              >{{ comAuditName(supplierInfo.audit_status) }}</view
            >
            <view class="action-btn switch-btn" @click="showShopList = true"
              >切换店铺</view
            >
          </view>
        </div>
      </view>
    </view>

    <!-- 店铺切换弹窗 -->
    <view class="shop-list-popup" v-if="showShopList">
      <view class="popup-mask" @click="showShopList = false"></view>
      <view class="popup-content">
        <view
          class="shop-list-item"
          v-for="(shop, index) in supplierList"
          :key="index"
        >
          <view class="shop-list-info">
            <image class="shop-list-logo" :src="shop.logo" mode="fill"></image>
            <view class="shop-list-detail">
              <view class="shop-list-name">{{ shop.name }}</view>
              <view class="shop-list-address">{{ shop.address }}</view>
            </view>
          </view>
          <view class="shop-distance">{{ (shop.distance / 1000).toFixed(2) }}km</view>
          <view class="switch-shop-btn" @click="switchShop(shop.id)">切换</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getGoodsList, bindSupplier } from "@/apiShop/supplier";
import { getAroundSupplierListWithBrand } from "@/apiShop/home";
import { showToast } from "@/utils/helper";

// 商品列表数据
const companyInfoHeight = ref(0);
const shopFooterHeight = ref(0);
const scrollHeight = computed(() => {
  const windowHeight = getApp().globalData.systemInfo.windowHeight;
  // 将rpx转换为px的比例
  const rpx2px = windowHeight / 750;
  
  // 如果元素高度还未获取到，使用默认值
  const companyHeight = companyInfoHeight.value || 60; // 默认60px
  const footerHeight = shopFooterHeight.value || 200; // 默认200px
  
  // 动态计算滚动区域高度 = 窗口高度 - 公司信息高度 - 店铺信息高度
  return (windowHeight - companyHeight - footerHeight) / rpx2px;
});

// 店铺切换弹窗显示状态
const showShopList = ref(false);

const goodsList = ref([]);
const supplierInfo = ref({});
const query = ref({
  page: 1,
  limit: 99,
});

// 获取元素高度的函数
const getElementHeight = () => {
  nextTick(() => {
    // 使用uni.createSelectorQuery获取元素高度
    const query = uni.createSelectorQuery();
    
    // 获取公司信息区域高度
    query.select('.company-info').boundingClientRect(data => {
      if (data) {
        companyInfoHeight.value = data.height;
      }
    }).exec();
    
    // 获取底部店铺信息高度
    query.select('.shop-footer').boundingClientRect(data => {
      if (data) {
        shopFooterHeight.value = data.height;
      }
    }).exec();
  });
};

// 在组件挂载后获取元素高度
onMounted(() => {
  getElementHeight();
});

// 监听品牌信息变化，重新计算高度
const updateHeight = () => {
  // 延迟一下，确保DOM已更新
  setTimeout(() => {
    getElementHeight();
  }, 300);
};

//通过品牌获取商品
const getGoodsListData = async (id, type="init") => {
  if(type == "init"){
    query.value.page = 1;
  }
  const res = await getGoodsList({
    supplier_info_id: supplierInfo.value.id,
    brand_id: id,
    ...query.value,
  });
  if(res.data.length == 0){
    showToast("没有更多数据了");
  }
  if (type === "init") {
    goodsList.value = res.data;
    // 数据加载完成后，更新高度
    updateHeight();
    return;
  }
  goodsList.value = [...goodsList.value, ...res.data];
};
const callPhone = (phone) => {
  uni.makePhoneCall({
    phoneNumber: phone,
  });
};
const bindSupplierClick = async () => {
  // 你确定要绑定吗？
  uni.showModal({
    title: "提示",
    content: "你确定要绑定该供应商吗？",
    success: async (res) => {
      if (res.confirm) {
        // 调用绑定接口
        await bindSupplier({
          supplier_info_id: supplierInfo.value.id,
        });
        showToast("申请成功,请等待供应商审核");
      }
    },
  });
};

const comAuditName = (status) => {
  switch (status) {
    case 0:
      return "申请绑定";
    case 1:
      return "审核中";
    case 2:
      return "已绑定";
  }
};
const loaction = ref({
  latitude: undefined,
  longitude: undefined,
});
// 店铺列表数据
const supplierList = ref([]);
// 获取附近的所有供应商
const getSupplierList = async (id = "") => {
  const res = await getAroundSupplierListWithBrand({
    user_lat: loaction.value.latitude,
    user_lng: loaction.value.longitude,
    limit: 99,
    page: 1,
    brand_id: id,
  });
  supplierList.value = res.data;
};
const switchShop = (id) => {
  showShopList.value = false;
  const index = supplierList.value.findIndex((item) => item.id == id);
  if (index !== -1) {
    supplierInfo.value = supplierList.value[index];
    getGoodsListData(brand_id.value);
  }
};

const toGoodsDetail = (id) => {
  uni.navigateTo({
    url: `/pagesShop/goods/goodsDetail?id=${id}&supplier_id=${supplierInfo.value.id}`,
  });
};
const loadMore = () => {
  query.value.page++;
  getGoodsListData(brand_id.value, "more");
}

const brand_id = ref("");
onLoad(async (options) => {
  loaction.value = getApp().globalData.location;
  brand_id.value = options?.id;
  await getSupplierList(brand_id.value);
  
  if (options.supplierInfo) {
    supplierInfo.value = JSON.parse(options.supplierInfo);
  } else {
    // 从分类来的,找到第一个带品牌的店铺注入
    const res = supplierList.value.find((item) => {
      const index = item.brand_data.find((brand) => brand.id == options.id);
      if (index === -1) return;
      return index;
    });
    if (!res) {
      uni.showModal({
        title: "提示",
        content: "当前品牌暂无供应商绑定,请更改品牌查看",
        showCancel: false,
        success: (res) => {
          uni.navigateBack();
        },
      });
    }
    supplierInfo.value = res;
    supplierInfo.value.brand_name = options.brand_name || "";
  }

  if (options.id) {
    await getGoodsListData(brand_id.value);
    // 数据加载完成后，延迟一下再次计算高度，确保DOM已完全渲染
    setTimeout(() => {
      getElementHeight();
    }, 500);
  }
});
</script>

<style lang="scss" scoped>
.product-page {
  min-height: 82vh;
  padding-bottom: 180rpx; // 为底部固定区域留出空间

  // 顶部公司信息
  .company-info {
    padding: 30rpx 20rpx;
    background-color: #fff;
    margin-bottom: 20rpx;

    .company-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      text-align: center;
      margin-bottom: 10rpx;
    }

    .brand-name {
      font-size: 28rpx;
      color: #f00;
      text-align: center;
    }
  }

  // 商品列表
  
  .product-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10rpx;

    .product-item {
      width: calc(100% / 3);
      padding: 10rpx;
      box-sizing: border-box;
      margin-bottom: 20rpx;

      .product-image {
        width: 100%;
        height: 240rpx;
        border-radius: 8rpx;
        background-color: #fff;
      }

      .product-title {
        margin-top: 10rpx;
        font-size: 28rpx;
        color: #333;
        text-align: center;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        height: 80rpx;
      }
    }
  }
  

  // 底部固定店铺信息
  .shop-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 20rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
    z-index: 10;

    .shop-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .shop-logo {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }

      .shop-detail {
        flex: 1;
        align-self: flex-start;

        .shop-name {
          font-size: 30rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 6rpx;
        }

        .shop-address {
          font-size: 24rpx;
          color: #999;
        }
      }
    }

    .shop-actions {
      display: flex;
      justify-content: space-between;
      margin: 10rpx 20rpx 0 0;

      .action-btn {
        flex: 1;
        height: 70rpx;
        line-height: 70rpx;
        text-align: center;
        border-radius: 35rpx;
        font-size: 26rpx;
        margin: 0 10rpx;

        &.contact-btn {
          background-color: #f0f0f0;
          color: #333;
        }

        &.order-btn {
          background-color: #ff6b6b;
          color: #fff;
        }

        &.switch-btn {
          background-color: #2196f3;
          color: #fff;
        }
      }
    }
  }

  // 店铺切换弹窗
  .shop-list-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;

    .popup-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.5);
    }

    .popup-content {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      background-color: #fff;
      border-radius: 20rpx 20rpx 0 0;
      padding: 30rpx 20rpx;
      max-height: 70vh;
      overflow-y: auto;

      .shop-list-item {
        display: flex;
        align-items: center;
        padding: 20rpx;
        width: 90%;
        border-bottom: 1px solid #f0f0f0;

        .shop-list-info {
          display: flex;
          align-items: center;
          flex: 1;

          .shop-list-logo {
            width: 80rpx;
            height: 80rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
          }

          .shop-list-detail {
            flex: 1;

            .shop-list-name {
              font-size: 28rpx;
              color: #333;
              margin-bottom: 6rpx;
            }

            .shop-list-address {
              font-size: 24rpx;
              color: #999;
            }
          }
        }

        .shop-distance {
          font-size: 24rpx;
          color: #999;
          margin-right: 20rpx;
        }

        .switch-shop-btn {
          width: 100rpx;
          height: 60rpx;
          line-height: 60rpx;
          text-align: center;
          background-color: #f0f0f0;
          color: #333;
          font-size: 24rpx;
          border-radius: 30rpx;
        }
      }
    }
  }
}
.empty-order {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80vh;
		flex-direction: column;
	}
</style>
